<?php

namespace app\shop\job;

use app\shop\enums\payment\OrderType;
use app\shop\enums\payment\TradeState;
use app\shop\library\pay\PayProvider;
use app\shop\logic\OrderLogic;
use app\shop\logic\RechargeLogic;
use app\shop\service\PaymentTradeService;
use Exception;
use think\queue\Job;
use Throwable;

class ConfirmOrderPayStatusJob extends BaseJob
{
    public static string $queue = 'confirm_order_pay_status';

    protected int $delay = 30;

    /**
     * 确认支付状态
     * @throws Exception
     */
    public function fire(Job $job, $data): void
    {
        $this->start($job, $data);

        $paymentId = $data['payment_id'] ?? 0;
        if (!$paymentId) {
            $this->noNeedJob($job, ['msg' => '第三方交易ID为空']);
            return;
        }

        $paymentTrade = (new PaymentTradeService())->getPaymentById($paymentId);
        if ($paymentTrade->isEmpty()) {
            $this->noNeedJob($job, ['msg' => '第三方交易查询为空']);
            return;
        }

        if ($paymentTrade->trade_state == TradeState::PAID) {
            $this->noNeedJob($job, ['msg' => '支付交易已成功']);
            return;
        }

        try {
            $payProvider = new PayProvider($paymentTrade->pay_way);
            $payResult   = $payProvider->query([
                'out_trade_no' => $paymentTrade->out_trade_no,
                'source'       => $paymentTrade->source,
            ]);

            $this->addJobLog("交易单号【 $paymentTrade->out_trade_no 】结果", $payResult);

            if (isset($payResult['trade_state']) && $payResult['trade_state'] == 'REFUND') {
                $this->noNeedJob($job, ['msg' => '支付交易已退款', 'pay_result' => $payResult]);
                return;
            }

            if (isset($payResult['trade_state']) && $payResult['trade_state'] == 'SUCCESS') {
                $paymentTrade->trade_no    = $payResult['transaction_id'];
                $paymentTrade->trade_state = TradeState::PAID;
                $paymentTrade->pay_result  = $payResult;
                $paymentTrade->save();

                // 处理订单数据
                switch ($paymentTrade->order_type) {
                    case OrderType::SHOP:
                        (new OrderLogic())->processShopOrder($paymentTrade->order_id);
                        break;
                    case OrderType::RECHARGE:
                        (new RechargeLogic())->processRechargeOrder($paymentTrade->order_id);
                        break;
                }

                $this->successJob($job);
            } else {
                if ($job->attempts() <= 3) {
                    $this->addJobLog("交易单号【 $paymentTrade->out_trade_no 】未完成支付", $payResult);
                    $this->delay += $this->delay * 2;
                    $job->release($this->delay);
                    return;
                } else {
                    $job->delete();
                }
            }
        } catch (Throwable $e) {
            $this->delay += $this->delay * 2;

            $this->exceptionJob($job, $data, $e);

            throw new Exception($e->getMessage());
        }
    }
}